package com.hnkywl.sts.action.htgl;

import com.google.gson.Gson;
import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.entity.djgl.Jydd;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Htmx;
import com.hnkywl.sts.entity.htgl.Xsht;
import com.hnkywl.sts.entity.jhgl.Bgjhhz;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.organ.Lj;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.entity.sys.Bm;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.xsgl.Xsd;
import com.hnkywl.sts.entity.zjgl.Bzj;
import com.hnkywl.sts.entity.zjgl.Hthk;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.htgl.CghtService;
import com.hnkywl.sts.service.htgl.XshtService;
import com.hnkywl.sts.service.jhgl.BgjhhzService;
import com.hnkywl.sts.service.jhgl.HkjhService;
import com.hnkywl.sts.service.organ.LjwhService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.WzbmService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.tjbb.BzjyjService;
import com.hnkywl.sts.service.zjgl.BzjService;
import com.hnkywl.sts.service.zjgl.HthkService;
import com.hnkywl.sts.util.POIUtil;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-8
 * Time: 下午1:41
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/htgl/cghtgl")
public class CghtglAction extends SimpleActionSupport {
    private CghtService cghtService;

    private XshtService xshtService;

    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;

    private LjwhService ljwhService;

    private BgjhhzService bgjhhzService;
    private CghtDao cghtDao;

    private BzjService bzjService;
    private BzjyjService bzjyjService;
    private HthkService hthkService;
    private WzbmService wzbmService;

    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;
    //类型
    private String cglx;
    //采购合同ID
    private Long cghtId;
    private Gg gg;

    //当前登录员工的公司ID
    private Long gsId;
    private String gsqc;
    private Long zggsId;
    private Yg yg;

    //采购合同
    private Cght cght;
    //销售合同
    private Xsht xsht;

    //查询条件
    private String zt;

    private Long hzfId;

    private Long ssbmId;

    private Long ssgsId;

    private Long cgrId;

    private Long wzjhId;

    private String wzjhType;

    private String htbh;

    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private Long htdyId;

    private Bm hthm;

    private String cghtHtbm;

    private String cghtEmwtime;

    private Date startDate;
    private Date endDate;

    private String htType;

    private Map<String, String> rzlx;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    private String wzbm;

    private String htmxIds;

    private String sm;

    private String bm;

    private Bgjhhz bgjhhz;
    private Hthk hthk;
    private Gsjg qyjg;

    private Long ljId;

    private Long jhId;

    private Lj lj;

    private String bzjbl;

    private Bzj bzj;
    private String xhtbm;
    private Date currentTime = new Date();
    private Date startTime;
    private String shzt;// 审核状态  yes /no
    private Boolean sfhdj;


    /**
     * 方法名:     采购合同查询
     * 功能描述:      查询采购合同
     * 输入参数:    <@param cglx 采购合同类型 采购入库，直达到货>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("cghtList")
    public void cghtList() {
        this.renderJson(this.cghtService.findAllCgHt(wzbm, zt, cglx, htbh, ssgsId, ssbmId, cgrId, hzfId, null, startDate, endDate, xhtbm, page, rows));
    }

    @Action("cght_into")
    public String cght_into() {
        endDate = new Date();
        return SUCCESS;
    }

    @Action("bgjjhzSearchList")
    public void bgjjhzSearchList() {
        this.renderJson(this.bgjhhzService.findBgjhhzList(sm, bm, startDate, endDate, page, rows));
    }

    @Action("cght_fkfsList")
    public void bghtFkfsList() {
        if (cghtId != null) {
            renderJson(cghtService.findBgFkfsList(cghtId));
        } else {
            renderJson(cghtService.findBgFkfsList(Long.parseLong("0")));
        }
    }

    @Action("cghtgl")
    public String cghtgl() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        startTime = sDaysAfterNowDate(7);
        return SUCCESS;
    }

    //   当前日期加减n天后的日期，返回String   (yyyy-mm-dd)
    private Date sDaysAfterNowDate(int n) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.add(Calendar.DAY_OF_MONTH, -n);
        return rightNow.getTime();
    }

    @Action("cghtSimpleList")
    public void cghtSimpleList() {
        String gysmc = this.request.getParameter("q");
        renderJson(this.cghtService.findAllSimpleCgHt(wzjhId, zt, htType, gysmc, page, rows));
    }

    @Action("bzjCghtList")
    public void bzjCghtList() {
        renderJson(this.cghtService.findAllBzjCgHt(wzjhId, zt, htType, null, page, rows));
    }

    @Action("bzjCghtListForZj")
    public void zjBzjCghtList() {
        renderJson(this.cghtService.findCghtForZjBzj(wzjhId, zt, htType, null, page, rows));
    }

    @Action("hthkCghtList")
    public void hthkCghtList() {
        renderJson(this.cghtService.findAllHthkCgHt(wzjhId, zt, htType, null, page, rows));
    }

    @Action("jzjsCghtList")
    public void jzjsCghtList() {
        renderJson(this.cghtService.findJzjsCgHt(page, rows));
    }


    //保供采购单选择保供合同
    @Action("bgcghtSimpleList")
    public void bgcghtSimpleList() {
        renderJson(this.cghtService.findAllSimpleBgCgHt(cghtId, zt, htType, page, rows));
    }

    @Action("cghtByProcessInstance")
    public void cghtByProcessInstance() {
        Cght cght;
        String processInstanceId = StringUtils.EMPTY;
        Execution execution = this.executionService.findExecutionById(executionId);
        if (execution != null) {
            cght = this.cghtService.findCghtDetailByProcessInstance(execution.getProcessInstance().getId());
            processInstanceId = execution.getProcessInstance().getId();
        } else {
            cght = this.cghtService.findCghtDetailByProcessInstance(executionId);
            processInstanceId = executionId;
        }
        String xyJson = "{'id':'" + cght.getId() + "','type':'CGHT','businessNo':'" + cght.getHtbm() + "','processInstanceId':'" + processInstanceId + "'}";
        this.renderText(xyJson);
    }

    /**
     * 方法名:     采购合同明细
     * 功能描述:      显示数据库协议名称
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Actions({@Action("cghtgl_content"), @Action("cghtgl_detail")})
    public String cghtContent() {
        try {
            yg = YgService.getCurrentYg();
            gsId = YgService.getCurrentYgGsId();
            gsqc = YgService.getCurrentYgZgGs();
            zggsId = YgService.getCurrentYgZgGsId();
            if (cghtId != null) {
                cght = this.cghtService.findCghtDetail(cghtId);
                if (cght.getLj() != null && cght.getLj().getCghtmb() != null)
                    htdyId = cght.getLj().getCghtmb().getId();
            } else {
                this.startDate = new Date();
                lj = this.ljwhService.find(ljId);
                //bgjhhz = bgjhhzService.find(jhId);
                xhtbm = "";
                Map<String, String> map = new HashMap<String, String>();
                // if (null != bgjhhz.getBgjhhzmxList() && bgjhhz.getBgjhhzmxList().size() > 0) {
                  /*  for (Bgjhhzmx bgjhhzmx : bgjhhz.getBgjhhzmxList()) {
                        if (StringUtils.isNotBlank(bgjhhzmx.getXsxt_htbm())) {
                            map.put(bgjhhzmx.getXsxt_htbm(), bgjhhzmx.getXsxt_htbm());
                        }
                    }*/
                if (null != map) {
                    for (String key : map.keySet()) {
                        xhtbm += key + ",";
                    }
                }
                if (StringUtils.isNotBlank(xhtbm)) {
                    xhtbm = xhtbm.substring(0, xhtbm.length() - 1);
                }
                //  }

                //  if (null != cght && null != cght.getLj()) {
                // Lj lj = this.ljwhService.find(cght.getLj().getId());
                if (null != lj && null != lj.getCghtmb()) {
                    htdyId = lj.getCghtmb().getId();
                    if (cght != null) {
                        cghtHtbm = cght.getHtbm();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                        cghtEmwtime = simpleDateFormat.format(cght.getLastUpdated());
                    }
                    //}
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
/*
    @Actions({@Action("cghtgl_content"), @Action("cghtgl_detail")})
    public String cghtContent() {
        try {
            yg = YgService.getCurrentYg();
            gsId = YgService.getCurrentYgGsId();
            gsqc = YgService.getCurrentYgZgGs();
            zggsId = YgService.getCurrentYgZgGsId();
            if (cghtId != null) {
                cght = this.cghtService.findCghtDetail(cghtId);
                if (cght.getLj() != null && cght.getLj().getCghtmb() != null)
                    htdyId = cght.getLj().getCghtmb().getId();
            } else {
                this.startDate = new Date();
                lj = this.ljwhService.find(ljId);
                bgjhhz = bgjhhzService.find(jhId);
                xhtbm = "";
                Map<String, String> map = new HashMap<String, String>();
                if (null != bgjhhz.getBgjhhzmxList() && bgjhhz.getBgjhhzmxList().size() > 0) {
                    for (Bgjhhzmx bgjhhzmx : bgjhhz.getBgjhhzmxList()) {
                        if (StringUtils.isNotBlank(bgjhhzmx.getXsxt_htbm())) {
                            map.put(bgjhhzmx.getXsxt_htbm(), bgjhhzmx.getXsxt_htbm());
                        }
                        if (StringUtils.isNotBlank(bgjhhzmx.getSfhdj())) {
                            if (bgjhhzmx.getSfhdj().trim().equals("是")) {
                                sfhdj = true;
                            }
                            if (bgjhhzmx.getSfhdj().trim().equals("否")) {
                                sfhdj = false;
                            }
                        }
                    }
                    if (null != map) {
                        for (String key : map.keySet()) {
                            xhtbm += key + ",";
                        }
                    }
                    if (StringUtils.isNotBlank(xhtbm)) {
                        xhtbm = xhtbm.substring(0, xhtbm.length() - 1);
                    }
                }

                if (null != lj && null != lj.getCghtmb()) {
                    htdyId = lj.getCghtmb().getId();
                    if (cght != null) {
                        cghtHtbm = cght.getHtbm();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                        cghtEmwtime = simpleDateFormat.format(cght.getLastUpdated());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
*/

    @Action("cghtgl_htmx")
    public void cghtmxContent() {
        this.renderJson(this.cghtService.findCghtmxContent(cghtId));
    }

    @Action("cghtgl_htmxtocgd")
    public void cghtmxContentForCgd() {
        this.renderJson(this.cghtService.findCghtmxContentForCgd(cghtId));
    }

    @Action("bgjhhzmx_htmx")
    public void bgjhhzmxContent() {
        this.renderJson(this.bgjhhzService.findBgjhhzmxContent(cghtId));
    }

    //保供采购单选择保供合同明细
    @Action("bgcghtgl_htmx")
    public void bgcghtmxContent() {
        this.renderJson(this.cghtService.findBgCghtmxContent(cghtId, htmxIds));
    }

    @Action("cghtgldetail_htmx")
    public void cghtmxDetail() {
        this.renderJson(this.cghtService.findCghtmxDetail(cghtId, page, rows));
    }

    @Action("cghtgldetail_htmx_exp")
    public String cghtmxExp() {
        List<Map> htmx = cghtService.findCghtmx(cghtId);
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        POIUtil poiUtil = new POIUtil(wb);
        //设置列宽
        sheet.setDefaultRowHeightInPoints(15);
        sheet.setDefaultColumnWidth((short) 15);
        HSSFCellStyle titleStyle = poiUtil.createHeader3HSSFCellStyle(wb);
        poiUtil.fillRow(sheet, titleStyle, 0, "物资编码", "物资名称", "规格型号", "单位", "产地", "数量", "记重方式", "含税单价", "不含税单价", "含税总金额");
        for (int i = 1; i < htmx.size() + 1; i++) {
            Map item = htmx.get(i - 1);
            poiUtil.fillRow(sheet, null, i, item.get("wzgg.code"), item.get("wzgg.name"), item.get("wzgg.ggxh"), item.get("wzgg.dw"),
                    item.get("cd.z"), item.get("sbsl"), item.get("jzfs.z"), item.get("hsj"), item.get("bhsj"), item.get("hsje"));
        }
        try {
            response.setContentType("application/x-download");
            String filedisplay = new String(("采购合同明细.xls").getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
        return null;
    }


    @Action("cght_print")
    public String zksqContentPrint() {
        if (cghtId != null) {
            cght = cghtService.findCghtglDetail(cghtId);
        } else {
            cght = new Cght();
        }

        bzj = bzjService.findBzjByCghtId(cghtId);
        hthk = hthkService.findHthkByCghtId(cghtId);
        if (null != this.cghtService.findCghtDetail(cghtId).getBgjhhz()) {
            qyjg = this.cghtService.findCghtDetail(cghtId).getBgjhhz().getLj().getXy().get(0);
        }
        return SUCCESS;
    }


    @Action("cghtgl_print_detail")
    public void cghtglPrintDetail() {
        Gson gson = new Gson();
        // List<Map> zkdmxList = this.zkdmxDao.findZkdmxList(zkdId);
        List<Map> htmxes = cghtDao.findHtmxList(cghtId);
        Double sl = 0d;
        Double hsje = 0d;
        String result;
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.0000");
        StringBuffer sbTable = new StringBuffer();
        if (null != htmxes) {
///**/<td style="font-size: 15px;">贴息(元)</td> <td style="font-size: 15px;">贴息率(%)</td> <td style="font-size: 15px;">保证金利率(%)</td> <td style="font-size: 15px;">保证金金额(元)</td>
            sbTable.append("<table class=\"tb intb\" style=\"width: 100%;\"><thead>");
            sbTable.append("<tr>");
            sbTable.append("<td>物资编码</td><td>品名</td><td>规格型号</td><td>产地</td>" +
                    "<td>数量</td><td>记重方式</td><td>含税单价</td><td>不含税单价(元)</td>" +
                    "<td>含税总金额(元)</td>  <td>备注</td>");
            sbTable.append("</tr></thead><tbody>");

            for (int i = 0; i < htmxes.size(); i++) {
                sbTable.append("<tr>");
                // 物资编码
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("code")) {
                    sbTable.append(htmxes.get(i).get("code"));
                }
                sbTable.append("</td>");
                //    品名
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("name")) {
                    sbTable.append(htmxes.get(i).get("name"));
                }
                sbTable.append("</td>");
                //  规格型号
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("ggxh")) {
                    sbTable.append(htmxes.get(i).get("ggxh"));
                }
                sbTable.append("</td>");
                //产地
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("cd")) {
                    sbTable.append(htmxes.get(i).get("cd"));
                }
                sbTable.append("</td>");

                // 数量
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("sl")) {
                  /* sbTable.append(htmxes.get(i).get("sl"));*/
                    Double msl = ((BigDecimal) htmxes.get(i).get("sl")).doubleValue();
                    sbTable.append(df.format(msl));
                    sl += msl;
                }
                sbTable.append("</td>");
                //记重方式
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("jzfs")) {
                    sbTable.append(htmxes.get(i).get("jzfs"));
                }
                sbTable.append("</td>");


                //含税价
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("hsj")) {
                    /*sbTable.append(htmxes.get(i).get("hsj"));*/
                    Double mhsj = ((BigDecimal) htmxes.get(i).get("hsj")).doubleValue();
                    sbTable.append(df.format(mhsj));

                }
                sbTable.append("</td>");


                //不含税价
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("bhsj")) {
                    /* sbTable.append(htmxes.get(i).get("bhsj"));*/
                    Double mbhsj = ((BigDecimal) htmxes.get(i).get("bhsj")).doubleValue();
                    sbTable.append(df.format(mbhsj));

                }
                sbTable.append("</td>");
                //含税金额
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("hsje")) {
                  /*  sbTable.append(htmxes.get(i).get("hsje"));*/
                    Double mhsje = ((BigDecimal) htmxes.get(i).get("hsje")).doubleValue();
                    sbTable.append(df.format(mhsje));
                    hsje += mhsje;
                }


/*
                //贴息
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("tx")) {
                   *//* sbTable.append(htmxes.get(i).get("tx"));*//*
                    Double mtx = ((BigDecimal)htmxes.get(i).get("tx")).doubleValue();
                    sbTable.append(df.format(mtx));
                }
                sbTable.append("</td>");
                //贴息率
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("txl")) {
                 *//*   sbTable.append(htmxes.get(i).get("txl"));*//*
                    Double mtxl = ((BigDecimal)htmxes.get(i).get("txl")).doubleValue();
                    sbTable.append(df.format(mtxl));

                }
                sbTable.append("</td>");
                //保证金利率
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("bzjll")) {
                   *//* sbTable.append(htmxes.get(i).get("bzjll"));*//*
                    Double mbzjll = ((BigDecimal)htmxes.get(i).get("bzjll")).doubleValue();
                    sbTable.append(df.format(mbzjll));
                }
                sbTable.append("</td>");
                //保证金金额
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("bzjje")) {
                  *//*sbTable.append(htmxes.get(i).get("bzjje"));*//*
                    Double mbzjje = ((BigDecimal)htmxes.get(i).get("bzjje")).doubleValue();
                    sbTable.append(df.format(mbzjje));
                    bzjje+=mbzjje;
                }
                sbTable.append("</td>");*/

                //备注
                sbTable.append("<td>");
                if (null != htmxes.get(i).get("bz")) {
                    sbTable.append(htmxes.get(i).get("bz"));
                }
                /*sbTable.append("</td>");
                sbTable.append("</td>");*/

                sbTable.append("</td>");

                sbTable.append("</tr>");
            }
            sbTable.append("<tr>");

            sbTable.append("<th colspan=\"4\">合计:");
            sbTable.append("</th>");

            sbTable.append("<td>");
            sbTable.append(df.format(sl));
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append(df.format(hsje));
            sbTable.append("</td>");

         /*   sbTable.append("<td>");
            sbTable.append("</td>");
            sbTable.append("<td>");
            sbTable.append("</td>");
            sbTable.append("<td>");
            sbTable.append("</td>");
            sbTable.append("<td>");
            sbTable.append(df.format(bzjje));
            sbTable.append("</td>");*/
//*
            sbTable.append("<td>");
            sbTable.append("</td>");

            sbTable.append("</tr>");
            sbTable.append("</tbody></table>");
        }
        renderHtml(sbTable.toString());
    }


    /**
     * 方法名:     保存采购合同
     * 功能描述:      保存数据库采购合同
     */
    @Action("add_cght")
    public void addCght() {
        try {
            initCght(cght);
            Cght cghtTemp = this.cghtService.saveCght(cght);
            //自动生成销售合同
            //xshtService.createXsht(cght);
            renderText("{\"statusCode\":\"200\",\"cghtId\":\"" + cghtTemp.getId() + "\", \"message\":\"保存采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 采购合同审核
     */
    @Action("cght_confrim")
    public void cghtConfrim() {
        try {
            String result = this.cghtService.cghtConfirm(cghtId, shzt);
            renderText("{\"statusCode\":\"200\", \"message\":\"" + result + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 方法名:     保存采购合同
     * 功能描述:      保存数据库采购合同
     * 输入参数:    <@param cght 采购合同>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("edit_cght")
    public void editCght() {
        try {
            Cght clone = this.cghtService.findCghtDetail(cght.getId());
            if ("xsms".equals(clone.getHtms())) {
                cghtService.editCghtForXs(cght);
            } else {
                String htbm = clone.getHtbm();
                ReflectionUtils.getInstance(clone, cght);
                initCght(clone);
                clone.setZt("ybc");
                this.cghtService.editCght(clone, htbm);
//            if (cght.getCglx().equals("zddh")) {
//                this.xshtService.createXsht(clone, xsht);
//            }
            }
            renderText("{\"statusCode\":\"200\", \"message\":\"保存采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    private void initCght(Cght cght) {
       /* if (cght.getWzjh() != null && cght.getWzjh().getId() == null) {
            cght.setWzjh(null);
        }*/
        if (cght.getLj() != null && cght.getLj().getId() == null) {
            cght.setLj(null);
        }
        if (cght.getHzf() != null && cght.getHzf().getId() == null) {
            cght.setHzf(null);
        }
        if (cght.getFkfs() != null && cght.getFkfs().getId() == null) {
            cght.setFkfs(null);
        }
        if (cght.getHtxz() != null && cght.getHtxz().getId() == null) {
            cght.setHtxz(null);
        }
//        if (cght.getZddhxsht() != null && cght.getZddhxsht().getId() == null) {
//            cght.setZddhxsht(null);
//        }
        if (cght.getSbgs() != null && cght.getSbgs().getId() == null) {
            cght.setSbgs(null);
        }
        if (cght.getSbbm() != null && cght.getSbbm().getId() == null) {
            cght.setSbbm(null);
        }
        if (cght.getSbr() != null && cght.getSbr().getId() == null) {
            cght.setSbr(null);
        }
        if (cght.getWlfgs() != null && cght.getWlfgs().getId() == null) {
            cght.setWlfgs(null);
        }
        if (cght.getWlfbm() != null && cght.getWlfbm().getId() == null) {
            cght.setWlfbm(null);
        }
        if (cght.getWlfry() != null && cght.getWlfry().getId() == null) {
            cght.setWlfry(null);
        }
        if (xsht != null && xsht.getFkfs() != null && xsht.getFkfs().getId() == null) {
            xsht.setFkfs(null);
        }
        if (cght.getHtmxList() != null) {
            for (Htmx htmx : cght.getHtmxList()) {
                if (htmx.getCd() != null && htmx.getCd().getId() == null) {
                    htmx.setCd(null);
                }
                if (htmx.getJzfs() != null && htmx.getJzfs().getId() == null) {
                    htmx.setJzfs(null);
                }
            }
        }
    }

    /**
     * 方法名:     提交采购合同
     * 功能描述:      提交采购合同审核
     * 输入参数:    <@param cghtId 采购合同ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("commit_cght")
    public void commitCght() {
        try {
            //先判断这个采购合同是否开具足够的保证金
            cght = this.cghtService.findCghtDetail(cghtId);
            if(cght.getHtmxList().size()==0){
                throw new RuntimeException("请维护采购合同明细！");
            }

            if(cght.getBzjfs()==null&&cght.getSfhdj()==null && cght.getHtms().equals("xxms")){
                throw new RuntimeException("请维护采购合同信息中的是否后定价和保证金方式！");
            }

            if (cght.getMxts() == null || cght.getTxl() == null) {
                throw new RuntimeException("采购合同信息中免息天数，贴息率不能为空请修改添加！");
            }

            if (StringUtils.equals("xsms", cght.getHtms())) {
                cght.setBzjfs(0);
                cght.setSfhdj(false);
             }

            // 判断是居中结算订单，还是不是居中结算订单
            if (null == cght.getExtension() || cght.getExtension().equals("normal")) {
                String checkResult;
                if (cght.getBzjfs().equals(2)) {
                    checkResult = cghtService.checkHthkFromCght1(cghtId);
                } else {
                    checkResult = cghtService.checkBzjFromCght(cght);
                }
                if ("".equals(checkResult)) {
                    if (this.flowService.checkFlowStart("采购合同流程")) {
                        String contain = StringUtils.EMPTY;
                        if (cght.getCreateDepartment().getId() == 30
                                || cght.getCreateDepartment().getId() == 26
                                || cght.getCreateDepartment().getId() == 27
                                || cght.getCreateDepartment().getId() == 28
                                || cght.getCreateDepartment().getId() == 29
                                || cght.getCreateDepartment().getId() == 8131
                                || cght.getCreateDepartment().getId() == 8132
                                || cght.getCreateDepartment().getId() == 8133
                                || cght.getCreateDepartment().getId() == 8134)
                            contain = "协议";
                        else if (cght.getWzjh() != null && cght.getWzjh().getXy() != null)
                            contain = "协议";
                        String processInstanceId = this.flowService.regTask(cght.getProcessInstanceId(), "采购合同流程", contain);
                        cght.setProcessInstanceId(processInstanceId);
                        cght.setZt("ytj");
                    } else {
                        cght.setZt("ytj");
                    }
                    this.cghtService.editCght(cght, cght.getHtbm());
                    this.bzjyjService.saveBzjyjByCght(cght);
                    renderText("{\"statusCode\":\"200\", \"message\":\"提交采购合同成功\"}");
                } else {
                    renderText("{\"statusCode\":\"300\", \"message\":\"" + checkResult + "\"}");
                }
            } else {
                String checkResult;
                Jydd jydd = cghtService.findJydd(cght.getXsxt_htbm());
                if (null != jydd.getDingdan_type() && jydd.getDingdan_type().equals("1")) {
                    checkResult = cghtService.checkBzjFromCght(cght);
                } else {
                    checkResult = cghtService.checkJzjsFromCght1(cghtId);
                }
                if ("".equals(checkResult)) {
                    this.cghtService.tjCght(cghtId);
                    renderText("{\"statusCode\":\"200\", \"message\":\"提交采购合同成功\"}");
                } else {
                    renderText("{\"statusCode\":\"300\", \"message\":\"" + checkResult + "\"}");
                }
            }
            xshtService.createXsht2(cght);
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    /**
     * 方法名:     删除采购合同
     * 功能描述:      删除数据库采购合同
     * 输入参数:    <@param cghtId 采购合同ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("delete_cght")
    public void delete_cght() {
        try {
            Cght cght = this.cghtService.deleteCght(cghtId);
            //if (cght.getCglx().equals("zddh") && cght.getZddhxsht() != null) {
            this.xshtService.deleteXshtByCght(cght.getId());
            //}
            renderText("{\"statusCode\":\"200\", \"message\":\"删除采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 方法名:     履约采购合同
     * 功能描述:      履约数据库采购合同
     * 输入参数:    <@param cghtId 采购合同ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("agree_cght")
    public void agree_cght() {
        try {
            this.cghtService.agreeCght(cghtId);
            renderText("{\"statusCode\":\"200\", \"message\":\"履约采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


/*    @Action("tj_cght")
    public void tj_cght() {
        try {

            String checkResult1;
            checkResult1 = cghtService.checkJzjsFromCght1(cghtId);
            if ("".equals(checkResult1)) {
                this.cghtService.tjCght(cghtId);
                renderText("{\"statusCode\":\"200\", \"message\":\"提交采购合同成功\"}");
            } else {
                renderText("{\"statusCode\":\"300\", \"message\":\"" + checkResult1 + "\"}");
            }

            //  renderText("{\"statusCode\":\"200\", \"message\":\"审核采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }*/

    /**
     * 方法名:     终止采购合同
     * 功能描述:      终止数据库采购合同
     * 输入参数:    <@param cghtId 采购合同ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("stop_cght")
    public void stop_cght() {
        try {
            this.cghtService.stopCght(cghtId);
            this.cghtService.findCghtDetail(cghtId);
            renderText("{\"statusCode\":\"200\", \"message\":\"终止采购合同成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action(value = "examineTask")
    public void examineTask() {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);

            Execution execution = this.executionService.findExecutionById(executionId);
            Cght cght = cghtService.findCghtDetailByProcessInstance(execution.getProcessInstance().getId());
            var.put("status", result);
            if (cght.getCreateDepartment().getId() == 30
                    || cght.getCreateDepartment().getId() == 26
                    || cght.getCreateDepartment().getId() == 27
                    || cght.getCreateDepartment().getId() == 28
                    || cght.getCreateDepartment().getId() == 29
                    || cght.getCreateDepartment().getId() == 8131
                    || cght.getCreateDepartment().getId() == 8132
                    || cght.getCreateDepartment().getId() == 8133
                    || cght.getCreateDepartment().getId() == 8134)
                var.put("contain", "协议");
            else if (cght.getWzjh() != null && cght.getWzjh().getXy() != null)
                var.put("contain", "协议");
            else
                var.put("contain", StringUtils.EMPTY);
            this.taskService.completeTask(taskId, var);


            if (cght.getZt().equals("ybc")) {
                cght.setZt("ytj");
                cghtService.editCght(cght, cght.getHtbm());
//                if (cght.getCglx().equals("zddh")) {
//                    Xsht xsht = cght.getZddhxsht();
//                    xsht = this.xshtService.findXshtDetail(xsht.getId());
//                    xsht.setZt("ytj");
//                    xshtService.editXsht(xsht, xsht.getHtbm());
//                }
            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                Cght cght = cghtService.findCghtDetailByProcessInstance(execution.getProcessInstance().getId());
                cght.setZt("ybc");
                cghtService.editCght(cght, cght.getHtbm());
//                if (cght.getCglx().equals("zddh")) {
//                    Xsht xsht = cght.getZddhxsht();
//                    xsht = this.xshtService.findXshtDetail(xsht.getId());
//                    xsht.setZt("ybc");
//                    xshtService.editXsht(xsht, xsht.getHtbm());
//                }
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }


    @Action("cght_tj_ck")
    public void cghtTjCk() {
        try {
            cghtService.cghtTjCk(cghtId);
            this.renderText("{\"statusCode\":\"200\", \"message\":\"提交仓储系统成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action("cghtgl_bzj")
    public void bzjDetail() {
        this.renderJson(this.cghtService.findbzjList(cghtId));
    }

   @Action("hqmxList")
    public void hqmxList() {
        try {
           this.renderJson(this.cghtService.findhqmxList(xhtbm));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"rows\":}");
        }
    }
 /*   @Action("hqmxList")
    public void hqmxList() {
        try {
            String result = this.cghtService.findhqmxList(xhtbm);
            renderText("{\"statusCode\":\"200\", \"message\":\"" + result + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }*/

/*    @Action("httk_sfkList")
    public void httkSfkList() {
        Xsd xsd = xsdService.findXsdDetail(xsdId);
        Qyjg kh = qyjgService.findQyjgDetail(xsd.getKh().getId());
        this.renderJson(this.xsdService.findXsdSkList(xsd, xsd.getKh().getId(), kh.getBzjfs(), 1, 999999999));
    }*/

    public String getShzt() {
        return shzt;
    }

    public void setShzt(String shzt) {
        this.shzt = shzt;
    }


    //=====================================================


    public Boolean getSfhdj() {
        return sfhdj;
    }

    public void setSfhdj(Boolean sfhdj) {
        this.sfhdj = sfhdj;
    }

    public Gsjg getQyjg() {
        return qyjg;
    }

    public void setQyjg(Gsjg qyjg) {
        this.qyjg = qyjg;
    }

    public Hthk getHthk() {
        return hthk;
    }

    public void setHthk(Hthk hthk) {
        this.hthk = hthk;
    }

    public String getCglx() {
        return cglx;
    }

    public void setCglx(String cglx) {
        this.cglx = cglx;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Long getCghtId() {
        return cghtId;
    }

    public void setCghtId(Long cghtId) {
        this.cghtId = cghtId;
    }

    public Long getGsId() {
        return gsId;
    }

    public void setGsId(Long gsId) {
        this.gsId = gsId;
    }

    public Long getWzjhId() {
        return wzjhId;
    }

    public void setWzjhId(Long wzjhId) {
        this.wzjhId = wzjhId;
    }

    public Lj getLj() {
        return lj;
    }

    public void setLj(Lj lj) {
        this.lj = lj;
    }

    public String getCghtHtbm() {
        return cghtHtbm;
    }

    public void setCghtHtbm(String cghtHtbm) {
        this.cghtHtbm = cghtHtbm;
    }

    public String getCghtEmwtime() {
        return cghtEmwtime;
    }

    public void setCghtEmwtime(String cghtEmwtime) {
        this.cghtEmwtime = cghtEmwtime;
    }

    public Yg getYg() {
        return yg;
    }

    public void setYg(Yg yg) {
        this.yg = yg;
    }

    public Cght getCght() {
        return cght;
    }

    public void setCght(Cght cght) {
        this.cght = cght;
    }

    public Xsht getXsht() {
        return xsht;
    }

    public void setXsht(Xsht xsht) {
        this.xsht = xsht;
    }

    public String getHtbh() {
        return htbh;
    }

    public void setHtbh(String htbh) {
        this.htbh = htbh;
    }

    public Long getSsgsId() {
        return ssgsId;
    }

    public void setSsgsId(Long ssgsId) {
        this.ssgsId = ssgsId;
    }

    public Long getSsbmId() {
        return ssbmId;
    }

    public void setSsbmId(Long ssbmId) {
        this.ssbmId = ssbmId;
    }

    public Long getCgrId() {
        return cgrId;
    }

    public void setCgrId(Long cgrId) {
        this.cgrId = cgrId;
    }

    public String getWzjhType() {
        return wzjhType;
    }

    public void setWzjhType(String wzjhType) {
        this.wzjhType = wzjhType;
    }

    public Long getHzfId() {
        return hzfId;
    }

    public void setHzfId(Long hzfId) {
        this.hzfId = hzfId;
    }

    public String getZt() {
        return zt;
    }

    public void setZt(String zt) {
        this.zt = zt;
    }

    public Long getZggsId() {
        return zggsId;
    }

    public void setZggsId(Long zggsId) {
        this.zggsId = zggsId;
    }

    public String getGsqc() {
        return gsqc;
    }

    public void setGsqc(String gsqc) {
        this.gsqc = gsqc;
    }

    public String getResult() {
        return result;
    }

    public String getHtmxIds() {
        return htmxIds;
    }

    public void setHtmxIds(String htmxIds) {
        this.htmxIds = htmxIds;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public Long getHtdyId() {
        return htdyId;
    }

    public void setHtdyId(Long htdyId) {
        this.htdyId = htdyId;
    }

    public Bm getHthm() {
        return hthm;
    }

    public void setHthm(Bm hthm) {
        this.hthm = hthm;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getHtType() {
        return htType;
    }

    public void setHtType(String htType) {
        this.htType = htType;
    }

    public Map<String, String> getRzlx() {
        return rzlx;
    }

    public void setRzlx(Map<String, String> rzlx) {
        this.rzlx = rzlx;
    }

    public String getWzbm() {
        return wzbm;
    }

    public void setWzbm(String wzbm) {
        this.wzbm = wzbm;
    }

    public String getSm() {
        return sm;
    }

    public void setSm(String sm) {
        this.sm = sm;
    }

    public String getBm() {
        return bm;
    }

    public void setBm(String bm) {
        this.bm = bm;
    }

    public Bgjhhz getBgjhhz() {
        return bgjhhz;
    }

    public void setBgjhhz(Bgjhhz bgjhhz) {
        this.bgjhhz = bgjhhz;
    }

    public Long getLjId() {
        return ljId;
    }

    public void setLjId(Long ljId) {
        this.ljId = ljId;
    }

    public Long getJhId() {
        return jhId;
    }

    public void setJhId(Long jhId) {
        this.jhId = jhId;
    }

    public String getBzjbl() {
        return bzjbl;
    }

    public void setBzjbl(String bzjbl) {
        this.bzjbl = bzjbl;
    }

    public Bzj getBzj() {
        return bzj;
    }

    public void setBzj(Bzj bzj) {
        this.bzj = bzj;
    }

    public String getXhtbm() {
        return xhtbm;
    }

    public void setXhtbm(String xhtbm) {
        this.xhtbm = xhtbm;
    }

    public Date getCurrentTime() {
        return currentTime;
    }

    public void setCurrentTime(Date currentTime) {
        this.currentTime = currentTime;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    @Autowired
    public void setCghtService(CghtService cghtService) {
        this.cghtService = cghtService;
    }

    @Autowired
    public void setXshtService(XshtService xshtService) {
        this.xshtService = xshtService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }

    @Autowired
    public void setLjwhService(LjwhService ljwhService) {
        this.ljwhService = ljwhService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setBgjhhzService(BgjhhzService bgjhhzService) {
        this.bgjhhzService = bgjhhzService;
    }

    @Autowired

    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }


    @Autowired
    public void setBzjService(BzjService bzjService) {
        this.bzjService = bzjService;
    }

    @Autowired
    public void setBzjyjService(BzjyjService bzjyjService) {
        this.bzjyjService = bzjyjService;
    }

    @Autowired
    public void setHthkService(HthkService hthkService) {
        this.hthkService = hthkService;
    }
    @Autowired
    public void setWzbmService(WzbmService wzbmService) {
        this.wzbmService = wzbmService;
    }

    public Gg getGg() {
        return gg;
    }

    public void setGg(Gg gg) {
        this.gg = gg;
    }
}
